<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
    private $_id;
    public $user; //用户信息
    public $userId;//重写userid
    public $admin;
    /**
     * Authenticates username and password
     * @return boolean CUserIdentity::ERROR_NONE if successful authentication
     */
    public function authenticate() {
        $username = trim($this->username);
        //如果没有查询出来数据 则会返回null  通过用户名查出账户
        $user = User::model()->findByAttributes(array('username'=>CHtml::encode($username),'is_system'=>1));

        if ($user === null) {
            $this->errorCode = self::ERROR_USERNAME_INVALID;
            return false;
        } elseif (sha1($this->password.$user->salt) !== $user->password) {
            $this->errorCode = self::ERROR_PASSWORD_INVALID;
            return false;
        } else {
            $role_info = Role::model()->findByPk($user->role);
            $city_info = CreateCity::model()->findByPk($user->belong_city);
            //登录成功 表明用户密码正确而且账号存在
            //设置session过期时间   为session设置秒数 + 现在时间
            $this->setState('adminSessionTimeout', time()+3600);
            //验证成功
            $this->errorCode=self::ERROR_NONE;
            //把管理员ID写入session
            $this->setState('admin_id',$user->id);
            $this->setState('username',$user->username);
            $this->setState('city',$user->belong_city);
            $this->setState('role',$user->role);
            $this->setState('role_title',$role_info->title);
            $this->setState('city_title',$city_info->cn_name);
            $this->setState('city_en',$city_info->en_name);
            $this->_id = $user->id;
            $this->userId = $user->id;
        }
        return !$this->errorCode;
    }


    /**
     *
     * @return integer id of the logged user, null if not set
     */

    public function getUser()
    {
        return $this->admin;
    }

    public function getId()
    {
        return $this->_id;
    }

    public function getUserName()
    {
        return $this->username;
    }

    public function setUser(CActiveRecord $user)
    {
        $this->admin=$user->attributes;
    }
}